package com.studyroom.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.ApiResponse;
import com.studyroom.common.Result;
import com.studyroom.entity.Reservation;
import com.studyroom.service.ReservationService;
import com.studyroom.dto.SearchDTO;
import com.studyroom.utils.JwtTokenUtil;
import com.studyroom.vo.ReservationVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/reservations")
public class ReservationController {

    private static final Logger log = LoggerFactory.getLogger(ReservationController.class);

    @Autowired
    private ReservationService reservationService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/search")
    public Result<IPage<Reservation>> search(@RequestBody SearchDTO params) {
        return Result.success(reservationService.search(params));
    }

    @PutMapping("/{id}/end")
    public Result<Boolean> endReservation(@PathVariable Long id) {
        return Result.success(reservationService.endReservation(id));
    }

    @GetMapping("/my")
    public Result<Page<Reservation>> getMyReservations(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {
            
        // 参数校验
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }
        
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            
            Page<Reservation> reservationPage = reservationService.getMyReservations(username, status, new Page<>(page, size));
            
            // 打印响应数据
            if (reservationPage.getRecords() != null && !reservationPage.getRecords().isEmpty()) {
                System.out.println("\n=== Response Data Before Sending ===");
                System.out.println("First Record CreatedAt: " + reservationPage.getRecords().get(0).getCreatedAt());
                System.out.println("CreatedAt Type: " + reservationPage.getRecords().get(0).getCreatedAt().getClass().getName());
                System.out.println("=================================\n");
            }
            
            return Result.success(reservationPage);
        }
        return Result.error("获取预约列表失败");
    }

    @PostMapping
    public Result save(@RequestBody Reservation reservation) {
        // 添加日志
        log.info("收到预约请求: {}", reservation);
        
        try {
            reservationService.save(reservation);
            return Result.success();
        } catch (Exception e) {
            log.error("预约失败:", e);
            return Result.error("预约失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}/cancel")
    public Result<?> cancelReservation(@PathVariable Long id,
                                     @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            reservationService.cancelReservation(username, id);
            return Result.success("取消成功");
        }
        return Result.error("取消预约失败");
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteReservation(@PathVariable Long id) {
        try {
            // 删除预约时需考虑更新座位状态
            reservationService.deleteReservation(id);
            return ResponseEntity.ok(new ApiResponse(true, "预约删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse(false, "删除失败: " + e.getMessage()));
        }
    }

    /**
     * 检查用户预约冲突
     */
    @PostMapping("/user/conflicts")
    public Result<List<ReservationVO>> checkUserConflicts(@RequestBody Map<String, Object> params) {
        try {
            Long userId = Long.parseLong(params.get("userId").toString());
            LocalDateTime startTime = LocalDateTime.parse(params.get("startTime").toString(), 
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            LocalDateTime endTime = LocalDateTime.parse(params.get("endTime").toString(), 
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            
            @SuppressWarnings("unchecked")
            List<Integer> statusList = (List<Integer>) params.get("statusList");
            
            // 查询用户在指定时间段内的预约
            List<ReservationVO> conflictReservations = reservationService.getUserConflictReservations(
                userId, startTime, endTime, statusList);
            
            return Result.success(conflictReservations);
        } catch (Exception e) {
            log.error("检查用户预约冲突失败", e);
            return Result.error("检查冲突失败: " + e.getMessage());
        }
    }

    @GetMapping("/user/cancelled/count")
    public Result<Integer> getUserCancelledCount(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            Integer count = reservationService.getUserCancelledCountLastWeek(username);
            return Result.success(count);
        }
        return Result.error("获取用户取消预约次数失败");
    }
} 